use axum::{extract::{ws::{Message, WebSocket}, WebSocketUpgrade}, response::Response};

use crate::global::APP;


pub async fn on_status_connect(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle)
}

async fn handle(mut socket: WebSocket) {

    let mut rx = APP.subscribe();
    
    loop {
        
        let item = tokio::select! {
            _ = socket.recv() => {
                break;
            },
            item = rx.recv() => {
                item
            }    
        };

        let bytes = match item {
            Ok(item) => item,
            Err(e) => {
                log::error!("recv:{}", e);
                break;
            }
        };

        if let Err(e) = socket.send(Message::Binary(bytes)).await {
            log::error!("send:{}", e);
            break;
        }

    }
    log::info!("ws exit");
}





